package com.example.crossborderecommerce.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.crossborderecommerce.entity.*;
import com.example.crossborderecommerce.mapper.PurchaseOrderMapper;
import com.example.crossborderecommerce.service.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 采购订单模块
 *
 * @author Yolanda
 * @since 2024-05-09
 */
@RestController
@Transactional
@RequestMapping("/purchase-order")
public class PurchaseOrderController {
    @Resource
    IPurchaseOrderService purchaseOrderService;
    @Resource
    IProductService productService;
    @Resource
    IStoreService storeService;
    @Resource
    ISupplierService supplierService;
    @Resource
    IAdminService adminService;
    @Resource
    PurchaseOrderMapper purchaseOrderMapper;


    /**
     * 添加采购订单
     * @param purchaseOrder
     * @return
     */
    @PostMapping("/save")
    public Result save(@RequestBody PurchaseOrder purchaseOrder){
        boolean res = purchaseOrderService.save(purchaseOrder);
        if(res){
            return Result.success("添加采购订单成功！");
        }
        return Result.error("添加采购订单失败！");
    }

    /**
     * 删除采购订单
     * @param purchaseOrder
     * @return
     */
    @PostMapping("/delete")
    public Result delete(@RequestBody PurchaseOrder purchaseOrder){
        boolean res = purchaseOrderService.removeById(purchaseOrder);
        if(res){
            return Result.success("删除采购订单成功！");
        }
        return Result.error("删除采购订单失败！");
    }

    /**
     * 删除一系列采购订单
     * @param ids
     * @return
     */
    @GetMapping("/deleteBatch")
    public Result deleteBatch(@RequestParam String ids) {
        List<String> purchaseOrderIds = Arrays.stream(ids.split(",")).collect(Collectors.toList());
        boolean res = purchaseOrderService.removeByIds(purchaseOrderIds);
        if(res) {
            return Result.success("删除采购订单成功");
        }
        return Result.error("删除采购订单失败！");
    }

    /**
     * 查询所有采购订单
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll() {
        List<PurchaseOrder> purchaseOrderList = purchaseOrderService.list();
        if(purchaseOrderList == null) {
            return Result.error("获取全部采购订单失败！");
        }
        for(PurchaseOrder purchaseOrder : purchaseOrderList) {
            if(purchaseOrder.getAdminId() != null) {
                Admin admin = adminService.getById(purchaseOrder.getAdminId());
                purchaseOrder.setAdminName(admin.getName());
            }
        }
        return Result.success("获取全部采购订单成功！", purchaseOrderList);
    }

    /**
     * 修改采购订单
     * @param purchaseOrder
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody PurchaseOrder purchaseOrder) {
        // 设置更新时间为当前时间
        purchaseOrder.setUpdateTime(LocalDateTime.now());
        boolean res = purchaseOrderService.saveOrUpdate(purchaseOrder);
        if (res) {
            return Result.success("修改采购订单成功！");
        }
        return Result.error("修改采购订单失败！");
    }

    /**
     * 获取全部采购订单
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/findPage")
    public Result findPage(@RequestParam(defaultValue = "-1") String supplierId,
                           @RequestParam(defaultValue = "-1") String storeId,
                           @RequestParam(defaultValue = "") String productName,
                           @RequestParam(defaultValue = "") String timeFrom,
                           @RequestParam(defaultValue = "") String timeTo,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        Page<PurchaseOrder> purchaseOrderPage = new Page<>(pageNum, pageSize);
        List<PurchaseOrder> purchaseOrderList = purchaseOrderMapper.getPurchaseOrderByPage(purchaseOrderPage, supplierId, storeId, productName, timeFrom, timeTo);
        for(PurchaseOrder purchaseOrder : purchaseOrderList) {
            if(purchaseOrder.getAdminId() !=null){
                Admin admin = adminService.getById(purchaseOrder.getAdminId());
                purchaseOrder.setAdminName(admin.getName());
            }
            if(purchaseOrder.getStoreId() != null) {
                Store store = storeService.getById(purchaseOrder.getStoreId());
                purchaseOrder.setStoreName(store.getName());
            }
            if(purchaseOrder.getProductId() != null) {
                Product product = productService.getById(purchaseOrder.getProductId());
                purchaseOrder.setProductName(product.getName());
            }
            if(purchaseOrder.getSupplierId() != null) {
                Supplier supplier=supplierService.getById(purchaseOrder.getSupplierId());
                purchaseOrder.setSupplierName(supplier.getName());
            }
        }
        Page<PurchaseOrder> newPurchaseOrderPage = new Page<>(pageNum, pageSize);
        newPurchaseOrderPage.setRecords(purchaseOrderList);
        newPurchaseOrderPage.setTotal(purchaseOrderPage.getTotal());
        return Result.success("成功查询所有采购订单！",newPurchaseOrderPage);
    }

    /**
     * 查询采购订单中所有联系人
     * @return
     */
    @GetMapping("/findAdminsInPurchaseOrder")
    public Result findAdminsInPurchaseOrder() {
        List<Admin> adminList = purchaseOrderService.findAdminsInPurchaseOrder();
        if(adminList == null) {
            return Result.error("获取联系人信息失败！");
        }
        return Result.success(adminList);
    }

    /**
     * 导出采购订单
     * @param response
     * @return
     */
    @GetMapping("exportPurchasrOrderList")
    public Result exportPurchaseOrderList(@RequestParam(defaultValue = "-1") String supplierId,
                                         @RequestParam(defaultValue = "-1") String storeId,
                                         @RequestParam(defaultValue = "") String productName,
                                         @RequestParam(defaultValue = "") String timeFrom,
                                         @RequestParam(defaultValue = "") String timeTo,
                                         HttpServletResponse response) {
        QueryWrapper<PurchaseOrder> queryWrapper = new QueryWrapper<>();
        List<PurchaseOrder> purchaseOrderList = purchaseOrderService.list(queryWrapper);
        for(PurchaseOrder purchaseOrder : purchaseOrderList) {
            if(purchaseOrder.getAdminId() !=null){
                Admin admin = adminService.getById(purchaseOrder.getAdminId());
                purchaseOrder.setAdminName(admin.getName());
            }
            if(purchaseOrder.getStoreId() != null) {
                Store store = storeService.getById(purchaseOrder.getStoreId());
                purchaseOrder.setStoreName(store.getName());
            }
            if(purchaseOrder.getProductId() != null) {
                Product product = productService.getById(purchaseOrder.getProductId());
                purchaseOrder.setProductName(product.getName());
            }
            if(purchaseOrder.getSupplierId() != null) {
                Supplier supplier=supplierService.getById(purchaseOrder.getSupplierId());
                purchaseOrder.setSupplierName(supplier.getName());
            }
        }
        HSSFWorkbook wb = new HSSFWorkbook(); // 导出到excel文件中
        HSSFSheet sheet = wb.createSheet("表一");
        HSSFRow row = sheet.createRow(0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        HSSFCell cell = row.createCell((short) 0);
        cell.setCellValue("ID");
        cell.setCellStyle(style);
        cell = row.createCell((short) 1);
        cell.setCellValue("产品名称");
        cell.setCellStyle(style);
        cell = row.createCell((short) 2);
        cell.setCellValue("采购数量");
        cell.setCellStyle(style);
        cell = row.createCell((short) 3);
        cell.setCellValue("花费金额");
        cell.setCellStyle(style);
        cell = row.createCell((short)4);
        cell.setCellValue("仓库名称");
        cell.setCellStyle(style);
        cell = row.createCell((short)5);
        cell.setCellValue("供应商");
        cell.setCellStyle(style);
        cell = row.createCell((short)6);
        cell.setCellValue("联系人");
        cell.setCellStyle(style);
        cell = row.createCell((short)7);
        cell.setCellValue("联系电话");
        cell.setCellStyle(style);
        cell = row.createCell((short)8);
        cell.setCellValue("采购时间");
        cell.setCellStyle(style);
        cell = row.createCell((short)9);
        cell.setCellValue("更新时间");
        cell.setCellStyle(style);
        SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0; i < purchaseOrderList.size(); i++) {
            row = sheet.createRow(i + 1);
            PurchaseOrder purchaseOrder = purchaseOrderList.get(i);
            row.createCell((short) 0).setCellValue(purchaseOrder.getId());
            row.createCell((short) 1).setCellValue(purchaseOrder.getProductName());
            row.createCell((short) 2).setCellValue(purchaseOrder.getQuantity());
            row.createCell((short) 3).setCellValue(purchaseOrder.getPrice());
            row.createCell((short) 4).setCellValue(purchaseOrder.getStoreName());
            row.createCell((short) 5).setCellValue(purchaseOrder.getSupplierName());
            row.createCell((short) 6).setCellValue(purchaseOrder.getAdminName());
            row.createCell((short) 7).setCellValue(purchaseOrder.getContactPhone());
            try {
                if(purchaseOrder.getCreateTime() != null) {
                    Date createTime = inputDateFormat.parse(purchaseOrder.getCreateTime().toString()); // 假设 getCreateTime 返回的是 String
                    row.createCell((short) 8).setCellValue(outputDateFormat.format(createTime));
                }
                if(purchaseOrder.getUpdateTime() != null) {
                    Date updateTime = inputDateFormat.parse(purchaseOrder.getUpdateTime().toString());
                    row.createCell((short) 9).setCellValue(outputDateFormat.format(updateTime));
                }
            } catch (ParseException e) {
                row.createCell((short) 8).setCellValue(purchaseOrder.getCreateTime().toString());
                row.createCell((short) 9).setCellValue(purchaseOrder.getUpdateTime().toString());
            }
        }
        String fileName = "exportPurchaseOrderList.xls";
        // 用户下载
        try {
            ServletOutputStream outputStream = null;
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8"));
            outputStream = response.getOutputStream();
            wb.write(outputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return Result.success("exportPurchaseOrderList");
    }
}
